package com.innovation.sys.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.sys.common.dto.RelationForAccountDTO;
import com.innovation.sys.common.utils.PasswordUtils;
import com.innovation.sys.common.vo.BaseException;
import com.innovation.sys.dao.SSxsRolespermissionsMapper;
import com.innovation.sys.dao.SSysAccountMapper;
import com.innovation.sys.dao.SSysAccountRolesMapper;
import com.innovation.sys.dao.SSysRolesMapper;
import com.innovation.sys.pojo.SSxsRolespermissions;
import com.innovation.sys.pojo.SSysAccount;
import com.innovation.sys.pojo.SSysAccountRoles;
import com.innovation.sys.pojo.SSysRoles;
import com.innovation.sys.service.AccountService;

@Service
public class AccountServiceImpl implements AccountService {

	private static Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

	@Resource
	private SSysAccountMapper sysAccountMapper;

	@Resource
	private SSxsRolespermissionsMapper permissionsMapper;

	@Resource
	private SSysAccountRolesMapper accountRolesMapper;

	@Resource
	private SSysRolesMapper rolesMapper;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int add(SSysAccount account) {
		int flag = 0;
		try {
			String password = PasswordUtils.encryptPassword(account.getUserName(), account.getPassword());
			account.setPassword(password);
			// 0禁用状态，1启用状态
			account.setStatus(1);
			// 0未删除，1删除
			account.setDelFlag(0);
			account.setCreateTime(new Date());
			// 判断是否插入成功
			flag = sysAccountMapper.add(account);
			if(flag < 1) {
				throw new BaseException("添加用户失败！");
			}else {
				this.reconciliation(account);
			}
		} catch (Exception e) {
			logger.info("添加用户失败");
			throw new BaseException("添加用户失败！");
		}
		return flag;
	}

	// 新增权限
	private void reconciliation(SSysAccount account) {
		try {
			String[] permission = account.getPermission();
			// 角色，用户角色，角色权限新增
			// 1.角色新增,新增的用户都为operator
			SSysRoles sSysRoles = new SSysRoles();
			sSysRoles.setrId(account.getAccountId());
			sSysRoles.setrName("operator");
			rolesMapper.insertSelective(sSysRoles);
			// 2.用户角色新增
			SSysAccountRoles sSysAccountRoles = new SSysAccountRoles();
			sSysAccountRoles.setArId(account.getAccountId());
			sSysAccountRoles.setaId(account.getAccountId());
			accountRolesMapper.insertSelective(sSysAccountRoles);
			for (String string : permission) {
				// 3.角色权限新增
				SSxsRolespermissions sSxsRolespermission = new SSxsRolespermissions();
				sSxsRolespermission.setRoleId(account.getAccountId());
				sSxsRolespermission.setPermissionId(Integer.valueOf(string));
				permissionsMapper.insertSelective(sSxsRolespermission);
			}
			// 新增用户默认有的权限
			SSxsRolespermissions sSxsRolespermission = new SSxsRolespermissions();
			sSxsRolespermission.setRoleId(account.getAccountId());
			sSxsRolespermission.setPermissionId(6);
			permissionsMapper.insertSelective(sSxsRolespermission);
		} catch (Exception e) {
			logger.info("添加用户权限失败");
			throw new BaseException("添加用户权限失败！");
		}
	}

	// 修改权限
	private void afterReconciliation(SSysAccount account) {
		try {
			// 查询已经存在的权限信息,删除原来的权限信息再插入新的权限
			List<RelationForAccountDTO> selectByRelation = sysAccountMapper.selectByRelation(account.getAccountId());
			// 删除原来该客户的角色，用户角色，角色权限
			// 1.删除角色
			rolesMapper.deleteByCriteria(account.getAccountId());
			// 2.删除用户角色
			accountRolesMapper.deleteByCriteria(account.getAccountId());
			// 删除角色权限
			for (RelationForAccountDTO relationForAccountDTO : selectByRelation) {
				if (relationForAccountDTO.getRoleId() != null && relationForAccountDTO.getPermissionId() != null) {
					SSxsRolespermissions sSxsRolespermissions = new SSxsRolespermissions();
					sSxsRolespermissions.setRoleId(relationForAccountDTO.getRoleId());
					sSxsRolespermissions.setPermissionId(relationForAccountDTO.getPermissionId());
					permissionsMapper.delete(sSxsRolespermissions);
				}
			}
			// 新增角色，用户角色，角色权限
			this.reconciliation(account);
		} catch (Exception e) {
			logger.info("修改用户权限失败");
			throw new BaseException("修改用户权限失败！");
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public PageInfo<Map<String, Object>> selectByOption(Map map, Integer pageNum, Integer pageSize) {
		int pageNo = pageNum == null ? 1 : pageNum;
		int pageSiz = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNo, pageSiz);
		List<Map<String, Object>> pList = sysAccountMapper.findAll(map);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(pList);
		return page;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int deleteOne(Integer accountId) {
		SSysAccount sSysAccount = new SSysAccount();
		sSysAccount.setAccountId(accountId);
		sSysAccount.setDelFlag(1);
		return sysAccountMapper.updateAccount(sSysAccount);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SSysAccount findOne(Integer accountId) {
		SSysAccount sSysAccount = new SSysAccount();
		sSysAccount.setAccountId(accountId);
		return sysAccountMapper.findOne(sSysAccount);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int updateOne(SSysAccount account) {
		int flag = 0;
		try {
			// 先更新用户信息，再更新权限
			account.setUpdateTime(new Date());
			flag = sysAccountMapper.updateAccount(account);
			if (flag < 1) {
				throw new BaseException("更新用户失败！");
			} else {
				this.afterReconciliation(account);
			}
		} catch (Exception e) {
			logger.info("更新用户失败");
			throw new BaseException("更新用户失败！");
		}
		return flag;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SSysAccount findByName(String name) {
		return sysAccountMapper.findByUsername(name);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public List<RelationForAccountDTO> findUserPermission(Integer accountId) {
		return sysAccountMapper.selectByRelation(accountId);
	}

}
